import React from 'react'

import { useEffect, useState } from 'react';

import { Card, Button, Table, Modal, Form, Input, Upload, message, Space, Popconfirm, Checkbox, Divider } from 'antd';
import { PlusOutlined, DeleteOutlined, FormOutlined, LoadingOutlined, EditOutlined, UserOutlined } from '@ant-design/icons';
import { getUserListRes, addUserRes, deleteUserRes, getUserRoleRes,setUserRoleRes } from "@/api/acl/user";
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';

let start = true;
export default function User() {
  let [searchForm] = Form.useForm();
  let [userList, setUserList] = useState([]);
  let [total, setTotal] = useState(0);
  let [page, setPage] = useState(1);
  let [limit, setLimit] = useState(3);
  const [isModalOpen, setIsModalOpen] = useState(false);
  let [form] = Form.useForm();
  let [id, setId] = useState("");
  let [search, setSearch] = useState("");
  let [selectKeys, setSelectKeys] = useState([]);
  let [isOpen, setIsOpen] = useState(false);
  let [isSetRole, setIsSetRole] = useState(false);
  let [roleForm] = Form.useForm();
  let [rolesList,setRolesList] = useState([]);
  const CheckboxGroup = Checkbox.Group;

  const [allRolesList, setAllRolesList] = useState([]);
  // const defaultCheckedList = ['Apple', 'Orange'];


  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>([]);
  const [indeterminate, setIndeterminate] = useState(false);
  const [checkAll, setCheckAll] = useState(false);


  useEffect(() => {
 
      getUserList(page, limit, search);
      // start  =false;
   
  },[])//数组不写默认是mounted和update


  async function getUserList(page: number, limit: number, search: string) {
    let result = await getUserListRes(page, limit, search);
    console.log(result);
    setUserList(result.items);
    setTotal(result.total);
    if (!result.items.length) {
      let p = page - 1;
      setPage(p);
      getUserList(p, limit, search);

    }
  }

  function editBtn(data: any) {
    showModal();
    form.setFieldsValue(data);


    setId(data.id);
  }

  function confirm(data: any) {
    return async function () {
      try {
        await deleteUserRes(data.id);
        getUserList(page, limit, search);
        message.success("删除成功")
      } catch (error) {
        message.error("删除失败")
      }
    }
  }

  async function setRoleBtn(data: any) {
    
    let result = await getUserRoleRes(data.id);
    // setRolesList(result.allRolesList);
    let valueList = result.allRolesList.map((item:any)=>({
      label:item.roleName,
      value:item.id
    }))
    setAllRolesList(valueList);
    let cList = result.assignRoles.map((item: any) => item.id);
    // console.log(result.allRolesList,cList,"数组");
    roleForm.setFieldsValue({username:data.username});
    setCheckedList(cList);
    setId(data.id);
    setIsSetRole(true);
    setIndeterminate(cList.length?true:false)
  }

  const columns: any = [
    {
      title: "序号",
      render: (txt: any, records: any, index: any) => {
        return index + 1
      },
      align: "center",
      width: 80
    },
    {
      title: "用户名",
      dataIndex: "username",
      align: "center",
      width: 150
    },
    {
      title: "用户昵称",
      dataIndex: "nickName",
      align: "center",
      width: 150
    },
    {
      title: "角色列表",
      dataIndex: "roleName",
      align: "center",

    },
    {
      title: "创建时间",
      dataIndex: "gmtCreate",
      align: "center",
      width: 250
    },
    {
      title: "更新时间",
      dataIndex: "gmtModified",
      align: "center",
      width: 250
    },
    {
      title: "操作",
      render: (data: any) => {
        return (
          <>
            <Space>
              <Button icon={<UserOutlined />} onClick={() => { setRoleBtn(data) }} style={{background:"#ccc"}}></Button>
              <Button type='primary' icon={<EditOutlined />} onClick={() => { editBtn(data) }} style={{background:"#E6A23C",borderColor:"#E6A23C"}}></Button>

              <Popconfirm
                title={`是否确认删除 用户 ${data.username} ？`}
                onConfirm={confirm(data)}

                okText="确定"
                cancelText="取消"
              >
                <Button type='primary' danger icon={<DeleteOutlined />}  ></Button>
              </Popconfirm>
            </Space>


          </>
        )
      },
      align: "center",
      fixed: "right",
      width: 200
    }

  ]




  // 多选框设置角色


  const onChange = (list: CheckboxValueType[]) => {   
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < allRolesList.length);
    setCheckAll(list.length === allRolesList.length);
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    let list = allRolesList.map((item:any)=>item.value)
    setCheckedList(e.target.checked ? list : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  // 发请求修改用户角色
  async function setRole(){
    let userId = id;
    // let checkedRole = rolesList.filter((item:any)=>{
    //   let flag = checkedList.some((value:any)=>value===item.roleName);
    //   return flag;
    // })

    // let roleId= (checkedRole.map((item:any)=>item.id)).join(",")
    let roleId = checkedList.join(",");
    try {
      await setUserRoleRes(userId,roleId as string);
      setIsSetRole(false);
      setId("");
      getUserList(page,limit,search);
      message.success("设置角色成功");

    } catch (error) {
      message.error("设置角色失败")
    }
  }

  const setRoleModal = (
    <>
      <Modal title="设置角色" visible={isSetRole} onOk={() => {setRole() }} onCancel={() => { setIsSetRole(false);setId("") }}>
        <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} form={roleForm}>
          <Form.Item label="用户名" name="username">
            <Input disabled></Input>
          </Form.Item>
          <Form.Item label="角色列表">
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <Divider />
            {/* options里的跟value需要对应上，而options需要遍历显示，所以只能是文本的值  那么value也只能是文本的值 */}
            <CheckboxGroup options={allRolesList} value={checkedList} onChange={onChange} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )




  const showModal = () => {

    setIsModalOpen(true);

  };

  const handleOk = () => {

    let data = form.getFieldsValue();
    data.id = id;
    form.validateFields().then(async value => {
      // value是校验的表单数据
      console.log("value", value);
      try {

        await addUserRes(data);
        setIsModalOpen(false);
        getUserList(page, limit, search);
        message.success(data.id ? "修改成功" : "添加成功");
        setId("");
        form.resetFields();

      } catch (error) {
        message.error(data.id ? "修改失败" : "添加失败")
      }
    })


  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setId("");
    form.resetFields();
  };






  return (
    <div>
      <Card>
      {setRoleModal}

        {/* 添加修改的对话框 */}
        <Modal title={id ? "修改用户" : "添加用户"} visible={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
          <Form labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} form={form}>
            <Form.Item label="用户名" name="username" rules={[{ required: true, message: "请输入用户名" }]}>
              <Input></Input>
            </Form.Item>
            <Form.Item label="用户昵称" name="nickName" rules={[{ required: true, message: "请输入用户昵称" }]}>
              <Input></Input>
            </Form.Item>
            {id ? "" : <Form.Item label="用户密码" name="password" rules={[{ required: true, message: "请输入密码" }, { min: 6, message: "至少6-16个字符，至少1个大写字母，1个小写字母和1个数字！", pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,16}$/ }]} >
              <Input></Input>
            </Form.Item>}

          </Form>
        </Modal>
        {/* 查询区 */}
        <Form form={searchForm} layout="inline" style={{ marginBottom: 20 }}>
          <Form.Item >
            <Input value={search} onChange={(e) => {
              setSearch(e.target.value);
            }}></Input>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={async () => {
              setPage(1);
              getUserList(1, limit, search);
            }}>查询</Button>
          </Form.Item>
          <Form.Item>
            <Button onClick={() => {
              setSearch("");
              setPage(1);
              getUserList(1, limit, "");
            }}>取消</Button>
          </Form.Item>
        </Form>
        <Button type="primary" style={{ marginRight: 20 }} onClick={showModal}>添加</Button>
        <Button type="primary" danger onClick={() => { setIsOpen(true) }} disabled={!selectKeys.length}>批量删除</Button>
        {/* 批量删除对话框 */}
        <Modal title="批量删除" visible={isOpen} onOk={async () => {
          let arr: any = [];
          try {
            selectKeys.forEach(item => {
              arr.push(deleteUserRes(item));
            })
            await Promise.all(arr);
            getUserList(page, limit, search);
            message.success("删除成功")

          } catch (error) {
            message.error("删除失败")
          }
          setIsOpen(false);
        }} onCancel={() => { setIsOpen(false) }}>
          <h4>是否确认批量删除？</h4>
        </Modal>





        <Table dataSource={userList} columns={columns} style={{ margin: "20px 0" }}
          bordered scroll={{ x: 1500 }}

          rowSelection={{
            // 这两个参数 第一个是所有选中的行的rowKey组成的数组   第二个参数是所有选中行的数据对象组成的数组
            onChange: (keyList: any, rowList: any) => {
              console.log(keyList, rowList);
              setSelectKeys(keyList);

            }
          }}




          pagination={{
            pageSize: limit,
            current: page,
            total,

            pageSizeOptions: [3, 5, 7, 10],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: (page, limit) => {
              setLimit(limit);
              setPage(page);
              getUserList(page, limit, search);
            },
            showTotal: (total) => {
              return `总共 ${total} 条`
            }
          }}
          rowKey="id"
        >

        </Table >
      </Card>
    </div>
  )
}
